;(function($){
    var adjustHeight = function(){
        $('.content-container').css('height',$(window).height()-40)
        $('.content').css('width',$(window).width()-180-11)
    }
    $(window).resize(adjustHeight)
    adjustHeight()     
})(jQuery)

var map;
var carstorelayer,highlightlayer;
var selectedFeature;
function init() {
    map= new OpenLayers.Map("rcp1_map");
    var osm = new OpenLayers.Layer.OSM();

    var styleMap= new OpenLayers.StyleMap({
        "default": new OpenLayers.Style(OpenLayers.Util.applyDefaults({
            fillColor: "green",
            fillOpacity:1,
            strokeColor: "black",
        }, OpenLayers.Feature.Vector.style["default"])),
        "select": new OpenLayers.Style(OpenLayers.Util.applyDefaults({
                fillColor:"blue",
                fillOpacity:1,
                strokeColor: "black",
            }, OpenLayers.Feature.Vector.style["select"]))});
            carstorelayer = new OpenLayers.Layer.Vector("Path Layer",{styleMap:styleMap});

            var highlightstyleMap= new OpenLayers.StyleMap({
                "default": new OpenLayers.Style(OpenLayers.Util.applyDefaults({
                    fillColor: "blue",
                    fillOpacity:1,
                    strokeColor: "blue",
                    strokeWidth:5,
                }, OpenLayers.Feature.Vector.style["default"]))});

                highlightlayer = new OpenLayers.Layer.Vector("Highlight Layer",{styleMap:highlightstyleMap});

                map.addLayers([osm,carstorelayer,highlightlayer]);
                //map.addControl(new OpenLayers.Control.LayerSwitcher());
                map.addControl(
                    new OpenLayers.Control.MousePosition({id:"wgs84_mouse"})
                );

                drawControls = {
                    select: new OpenLayers.Control.SelectFeature(
                        carstorelayer,
                        {
                            onSelect:onFeatureSelect,onUnselect:onFeatureUnselect,
                            clickout: true, toggle: false,
                            multiple: false, hover: false,
                            selectStyle: {strokeColor:"rgb(0,0,230)",fillOpacity:0.5},
                            box:false 
                        }
                    ),
                }

                for(var key in drawControls) {
                    map.addControl(drawControls[key]);
                } 

                var initbounds = new OpenLayers.Bounds();
                initbounds.extend(GeoToWebMercator(114.0687978 , 30.3720963 ));
                initbounds.extend(GeoToWebMercator(114.480813 ,  30.6855));
                map.zoomToExtent(initbounds,true);
                map.setCenter(initbounds.centerLonLat);
                //map.zoomToMaxExtent();

                //mouse move event
                map.events.register("mousemove", map, function(e) {
                    var latlon = map.getLonLatFromViewPortPx(e.xy) ;
                    var lat = Math.round(latlon.lat);
                    var lon = Math.round(latlon.lon);
                    var transcoord=WebMercatorToGeo(lon,lat);
                    var strlonlat="lon, lat: "+Math.round(transcoord.lon*1e3)/1e3 +", "+Math.round(transcoord.lat*1e3)/1e3;
                    OpenLayers.Util.getElement("wgs84_mouse").innerHTML =strlonlat;
                });
                //get car store data from service
                getCarstore();
}

function onPopupClose(evt) {
    drawControls["select"].unselect(selectedFeature);
}
function onFeatureSelect(feature) {
    clearHighlights();
    HighlightPoint(feature);
    selectedFeature = feature;
    popup = new OpenLayers.Popup.FramedCloud("chicken", 
        feature.geometry.getBounds().getCenterLonLat(),
        null,
        "<div style='font-size:.8em'> "+feature.attributes["storeName"]+"<br>电话: "+feature.attributes["phone"]+"</div><br><button type='button' id='popupButton' >预约</button>",
        null, true, onPopupClose);

    feature.popup = popup;
    map.addPopup(popup);
    $('#popupButton').click(onBookOrder);
}

function onBookOrder() {
    var now= new Date();
    localStorage.setItem("orderId",getOrderId(now,false));
    localStorage.setItem("orderTime",getTimeString(now,false));
    localStorage.setItem("storeId",selectedFeature.attributes["storeId"]);
    localStorage.setItem("storeName",selectedFeature.attributes["storeName"]);
    localStorage.setItem("carID",g_CarID);
    localStorage.setItem("carName",g_CarName);
    localStorage.setItem("carFactory",g_CarFactory);
    localStorage.setItem("userId",g_UserID);
    localStorage.setItem("userName",g_UserName);

//    g_SelectedCarstore.orderId=getOrderId(now,false);
//    g_SelectedCarstore.orderTime=getTimeString(now,false);
//    g_SelectedCarstore.storeId=selectedFeature.attributes["storeId"];
//    g_SelectedCarstore.carID=g_CarID;
//    g_SelectedCarstore.userId=g_UserID;

    drawControls["select"].unselect(selectedFeature);
    RedirectToBook();
} 

function getOrderId()
{
    var dt=new Date();
    var year,month,day,hour,min,sec,milisec;
    year=formatInt(dt.getFullYear());
    month=formatInt(dt.getMonth()+1);
    day=formatInt(dt.getDate());
    hour=formatInt(dt.getHours());
    min=formatInt(dt.getMinutes());
    sec=formatInt(dt.getSeconds());
    milisec=formatInt(dt.getMilliseconds());
    //return year+""+month+""+day+""+hour+""+min+""+sec+""+milisec;
    return year+""+month+""+day+""+hour+""+min+""+sec+""+milisec%10;
}

function onFeatureUnselect(feature) {
    map.removePopup(feature.popup);
    feature.popup.destroy();
    feature.popup = null;
}    
function switchToPan()
{
    for(key in drawControls) {
        var control = drawControls[key];
        control.deactivate();
    }
}

function httpGetAsync(theUrl, callback) { 
    var httpRequest = new XMLHttpRequest();
    httpRequest.onreadystatechange = function() {
        if (httpRequest.readyState == 4 && httpRequest.status == 200) {
            //if you fetch a file you can JSON.parse(httpRequest.responseText)
            var data = httpRequest.responseText;  
            if (callback) {
                callback(data);
            }                   
        }
    };

    httpRequest.open('GET', theUrl, true); 
    httpRequest.send(null);
}

function getCarstore()
{
    console.log("getting carstore data...");
    httpGetAsync('/storeserver/allstores', function(data) {
        //do something with your data
        console.log(data);
        drawCarstore(JSON.parse(data));
    });
}

function drawCarstore(msg)
{
    for(var j=0;j<msg.length;j++)
    {
        var msgj=msg[j];
        var lon=msgj.lon;
        var lat=msgj.lat;

        var point=GeoToWebMercator2(lon,lat);
        var attributes={"storeId":msgj.storeId,"storeName":msgj.storeName,"phone":msgj.phone};
        var feature=new OpenLayers.Feature.Vector(point,attributes);

        carstorelayer.addFeatures([feature]);
    }
    switchToSelect();
}

function getTimeString(dt,utcformat)
{
    var year,month,day,hour,min,sec;
    if(utcformat==true)
    {
        year=formatInt(dt.getUTCFullYear());
        month=formatInt(dt.getUTCMonth()+1);
        day=formatInt(dt.getUTCDate());
        hour=formatInt(dt.getUTCHours());
        min=formatInt(dt.getUTCMinutes());
        sec=formatInt(dt.getUTCSeconds());
    }
    else
    {
        year=formatInt(dt.getFullYear());
        month=formatInt(dt.getMonth()+1);
        day=formatInt(dt.getDate());
        hour=formatInt(dt.getHours());
        min=formatInt(dt.getMinutes());
        sec=formatInt(dt.getSeconds());
    }
    return year+"-"+month+"-"+day+" "+hour+":"+min+":"+sec;
}

function formatInt(e)
{
    if(e<10)
    {
        return "0"+e;
    }
    else
    {
        return e;
    }
}

function GeoToWebMercator2(Lon,Lat){
    var LonLat=GeoToWebMercator(Lon,Lat);
    return new OpenLayers.Geometry.Point(LonLat.lon,LonLat.lat);
}
function GeoToWebMercator(Lon, Lat){
    return new OpenLayers.LonLat(Lon, Lat).transform("EPSG:4326","EPSG:900913");
}

function WebMercatorToGeo(X, Y){
    return new OpenLayers.LonLat(X, Y).transform("EPSG:900913","EPSG:4326");
}

function clearHighlights()
{
    if(highlightlayer.features.length!=0)
    {
        highlightlayer.removeAllFeatures();
    }
}

function HighlightPoint(feature)
{
    var highlightfeature=new OpenLayers.Feature.Vector(feature.geometry);
    highlightlayer.addFeatures([highlightfeature]);
}

function clearCustomDrawings()
{
    if(carstorelayer.features.length!=0)
    {
        carstorelayer.removeAllFeatures();
    }
    clearHighlights();
    clearPopups();
}
function clearPopups()
{
    for(var i=0;i<map.popups.length;i++)
    {
        map.removePopup(map.popups[0]);
    }
}

function switchToControl(controlName)
{
    for(key in drawControls) {
        var control = drawControls[key];
        control.deactivate();
    }
    drawControls[controlName].activate();
}

function switchToSelect()
{
    switchToControl("select");
}

function allowPan(element) {
    var stop = !element.checked;
    for(var key in drawControls) {
        drawControls[key].handler.stopDown = stop;
        drawControls[key].handler.stopUp = stop;
    }
}

function TestClick(){
    RedirectToBook();
}
